package com.tao.lab.event.dispath.poster;

import com.tao.lab.Poster;
import com.tao.lab.event.dispath.EventBus;
import com.tao.lab.event.dispath.Subscription;

/**
 * @ProjectName: lab
 * @Package: com.tao.lab.event.dispath
 * @ClassName: AsyncPoster
 * @Description: java类作用描述
 * @Author: wangxf
 * @CreateDate: 2022/5/6 13:55
 * @UpdateUser: 更新者
 * @UpdateDate: 2022/5/6 13:55
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class AsyncPoster implements Runnable, Poster {
    private final PendingPostQueue queue;
    private final EventBus eventBus;

    public AsyncPoster(EventBus eventBus) {
        this.eventBus = eventBus;
        this.queue = new PendingPostQueue();
    }

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        this.queue.enqueue(pendingPost);
        this.eventBus.getExecutorService().execute(this);
    }

    public void run() {
        PendingPost pendingPost = this.queue.poll();
        if (pendingPost == null) {
            throw new IllegalStateException("No pending post available");
        } else {
            this.eventBus.invokeSubscriber(pendingPost);
        }
    }
}
